package arkham.net.messages;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;


/**
 * An info message is used to pass information between the client and the
 * server. The client typically sends a request to the server and the 
 * server will return a response via this info message. Requests and responses
 * are sent as text
 * @author ctheng
 *
 */
public class InfoMessage extends Message {

	private String request;
	private String response;
	
	public InfoMessage()
	{
		this("", "");
	}
	
	public InfoMessage(String request)
	{
		this(request, "");
	}

	public InfoMessage(String request, String response)
	{
		this.request = request;
		this.response = response;
	}

	/**
	 * @return the request
	 */
	public String getRequest() {
		return request;
	}

	/**
	 * @param request the request to set
	 */
	public void setRequest(String request) {
		this.request = request;
	}

	/**
	 * @return the response
	 */
	public String getResponse() {
		return response;
	}

	/**
	 * @param response the response to set
	 */
	public void setResponse(String response) {
		this.response = response;
	}

	@Override
	public byte[] toByteArray() {
		// format: request \0 response \0
		byte[] b = new byte[request.length() + response.length() + 2];
		System.arraycopy(request.getBytes(), 0, b, 0, request.length());
		b[request.length()] = 0;
		System.arraycopy(response.getBytes(), 0, b, request.length() + 1, response.length());
		b[b.length - 1] = 0;
		return b;
	}

	@Override
	public void fromByteArray(byte[] b) throws IOException
	{
		ByteArrayInputStream bais = new ByteArrayInputStream(b);
		InputStreamReader isr = new InputStreamReader(bais);
		StringBuffer sb1 = new StringBuffer();
		StringBuffer sb2 = new StringBuffer();
		char q;

		while ((q = (char)isr.read()) != '\0')
		{
			sb1.append(q);
		}
		
		while ((q = (char)isr.read()) != '\0')
		{
			sb2.append(q);
		}
		request = sb1.toString();
		response = sb2.toString();
	}

	@Override
	public int getId() {
		// TODO Auto-generated method stub
		return MessageType.INFO_MESSAGE.id();
	}
	
	@Override
	public String toString()
	{
		return request + "/" + response;
	}

}
